<?php
/**
 * @发布消息
 * @Author: Helloweba
 * @publish_direct.php
 */

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$config = getConfig();
$exchange = 'article';

// connection -> channel -> exchange -> publish -> close

$connection = new AMQPStreamConnection(
    $config['host'],
    $config['port'],
    $config['user'],
    $config['password']
);

$channel = $connection->channel();

$channel->exchange_declare($exchange, 'direct', false, false, false);

// 发送100条消息
for ($i = 0; $i < 100; $i++) {
    $cate = ['fantasy', 'military', 'history', 'romance'];
    $key = array_rand($cate);

    $arr = [
        'id' => 'message_' . $i,
        'content' => 'type_'. $cate[$key]
    ];
    $data = json_encode($arr);
    $msg = new AMQPMessage($data);

    $routing_key = $cate[$key];
    $channel->basic_publish($msg, $exchange, $routing_key);
    // Send history message: {"id":"message_41","content":"type_history"}
    echo 'Send '.$cate[$key].' message: ' . $data . PHP_EOL;
}

$channel->close();
$connection->close();
